package com.upeoe.lucrocrawler.crawler;

import com.upeoe.lucrocrawler.utils.DateKit;
import com.upeoe.lucrocrawler.utils.PropsKit;
import org.quartz.Job;
import org.quartz.JobDetail;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.impl.JobDetailImpl;
import org.quartz.impl.StdSchedulerFactory;
import org.quartz.impl.triggers.CronTriggerImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.ParseException;

/**
 * @author ven_hxz
 * @create 2016-05-26 下午4:57
 * Lucro crawl controller
 * <p>
 * > Timer crawl 定时爬取
 * > Hand crawl 手动爬取
 */
public class LucroCrawler implements Job {

    private static SchedulerFactory schedulerFactory = new StdSchedulerFactory();
    private static String JOB_NAME = "JOB_NAME";                                    //任务名称
    private static String JOB_GROUP_NAME = "JOB_GROUP_NAME";                        //任务分组名称
    private static String TRIGGER_GROUP_NAME = "TRIGGER_GROUP_NAME";                //定时器分组名称
    private static String CRAWLER_TIMER = PropsKit.getValue("crawler_timer");       //定时器定时的时间
    private static Logger logger = LoggerFactory.getLogger(LucroCrawler.class);

    /**
     * 手动指定日期爬取
     */
    public static void crawlByHand() {
        String dateFrom = PropsKit.getValue("datefrom");
        String dateTo = PropsKit.getValue("dateto");
        Crawler.me(dateFrom, dateTo);
    }

    /**
     * 执行定时器任务
     */
    public static void start() {
        try {
            Scheduler scheduler = schedulerFactory.getScheduler();
            JobDetail jobDetail = new JobDetailImpl(JOB_NAME, JOB_GROUP_NAME, LucroCrawler.class);
            CronTriggerImpl trigger = new CronTriggerImpl(JOB_NAME, TRIGGER_GROUP_NAME);

            trigger.setCronExpression(CRAWLER_TIMER);
            scheduler.scheduleJob(jobDetail, trigger);

            if (!scheduler.isShutdown()) {
                scheduler.start();
            }
        } catch (SchedulerException | ParseException e) {
            logger.error(e.getMessage());
        }
    }

    /**
     * 定时爬取数据
     */
    private static void autoCrawler() {
        java.util.Date yesterday = DateKit.getYesterdayDate();
        String var1 = DateKit.Date2Str(DateKit.subDate(yesterday, 1));  //dateFrom
        String var2 = DateKit.Date2Str(yesterday);                      //dateTo
        Crawler.me(var1, var2);
    }


    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        autoCrawler();
    }
}
